package j_redis

import (
	"config-client-v1/init/global"
	j_log "config-client-v1/init/j-log"
	"config-client-v1/utils/tools"
	"context"
	"github.com/go-redis/redis/v8"
	"log"
	"time"
)

var RedisDb *redis.Client

func init() {
	RedisDb = &redis.Client{}
}

func Start() {
	addr := global.AppConfig.Section("redis").Key("addr").String()
	pwd := global.AppConfig.Section("redis").Key("pwd").String()
	state := global.AppConfig.Section("redis").Key("state").String()
	dbNum, _ := global.AppConfig.Section("redis").Key("db").Int()
	if state == "on" {
		RedisDb = redis.NewClient(&redis.Options{
			Addr:         addr,
			Password:     pwd,   // no password set
			DB:           dbNum, // use default DB
			PoolSize:     16,
			MinIdleConns: 4,
			MaxConnAge:   time.Minute * 5,
		})
		_, err1 := RedisDb.Ping(context.Background()).Result()
		if err1 != nil {
			//RedisDb = &redis.Client{}
			_ = tools.WriteStringToLog(err1.Error(), "sys_error.log", "a")
			log.Fatalln("redis连接失败", err1)
			return
		}
		j_log.LogInfo([]interface{}{"redis connection is OK"})
	}
}
